//
//  db.swift
//  二次源
//
//  Created by 李建文 on 2016/12/7.
//  Copyright © 2016年 二次源. All rights reserved.
//

import Foundation

class dbController {
    
    var db:SQLiteDB!
    
    init() {
        //获取数据库实例
        db = SQLiteDB.sharedInstance
        //如果表还不存在则创建表（其中uid为自增主键）
        let result = db.execute(sql: "create table if not exists t_user(id integer primary key,uname varchar(20),uid varchar(20))")
        print(result)
//        //如果有数据则加载
//        initUser()
    }
    
    
    //从SQLite加载数据
    func getUserName()->String {
        var name:String? = nil
        let data = db.query(sql: "select * from t_user")
        if data.count > 0 {
            //获取最后一行数据显示
            let user = data[data.count - 1]
            name = (user["uname"] as? String)!
        }else{
            name=""
        }
        print("获取用户名")
        return name!
    }
    
    func getUserId()->String {
        var uid:String? = nil
        let data = db.query(sql: "select * from t_user")
        if data.count > 0 {
            //获取最后一行数据显示
            let user = data[data.count - 1]
            uid = (user["uid"] as? String)!
        }
        print("获取用户id")
        return uid!
    }
    
    //保存数据到SQLite
    func saveUser(uname:String, uid:String) {
        //插入数据库，这里用到了esc字符编码函数，其实是调用bridge.m实现的
        let sql = "insert into t_user(uname,uid) values('\(uname)','\(uid)')"
        print("sql: \(sql)")
        //通过封装的方法执行sql
        let result = db.execute(sql: sql)
        print("保存数据")
        print(result)
    }
    
    //删除所有数据
    func deleAll(){
        let sql = "delete from t_user"
        let result = db.execute(sql: sql)
        print("删除所有数据")
        print(result)
    }
    
    //删除表
    func deleTable(){
        let sql = "drop table t_user"
        let result = db.execute(sql: sql)
        print(result)
    }
    
}
